package com.firmboy.thread;

import org.junit.Test;

import java.util.ArrayList;

/**
 * 保证并发安全的三个特性的测试
 *
 * @author firmboy
 * @create 2018-05-04 上午11:22
 **/
public class ThreeTest {


    @Test
    public void tests() throws InterruptedException {

        final Count count = new Count();

        Runnable run = new Runnable() {
            @Override
            public void run() {
                for(int i = 0;i<1000;i++){
                    count.inc();
                }
            }
        };

        ArrayList<Thread> threads = new ArrayList<>();
        for (int i = 0;i<1000;i++){
            Thread thread = new Thread(run);
            threads.add(thread);
        }

        for (Thread thread:threads
             ) {
            thread.start();
            thread.join();
        }


        System.out.println("程序执行完成count="+count.getCount());


    }


    class Count{

        public int count;

        public void inc(){
            synchronized (Count.class){
                count++;
            }
        }

        public int getCount(){
            return count;
        }

    }

}
